from django.shortcuts import render, redirect
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
from django.views.decorators.csrf import csrf_exempt
from django.http import JsonResponse
from game.models import Game, Robot
from game.util import compile
from playai.settings import GAME_SCRIPT_ROOT
import os, subprocess, json


def index(request):
	games = Game.objects.all()
	return render(request, 'game/index.html', {"games": games})


def gamelist(request):
	games = Game.objects.all()
	return render(request, 'game/gamelist.html', {"games": games})


def game_index(request, game_url):
	game = Game.objects.get(url=game_url)
	user_robots = Robot.objects.filter(user=request.user, game=game)
	all_robots = Robot.objects.filter(game=game)
	return render(request, "game/game.html", {"game": game, "user_robots": user_robots, "all_robots": all_robots})


@login_required
def addRobot(request, game_url):
	name = request.POST["name"]
	user = request.user
	game = Game.objects.get(url=game_url)
	code = request.FILES["code"]
	code.name = "{0}-{1}-{2}.cpp".format(game.name, user.username, name)
	robot = Robot(name=name, user=user, game=game, code=code)
	robot.save()
	exe_file = compile(robot.code.name)
	if exe_file:
		os.remove(robot.code.name)
		robot.code.name = exe_file
		robot.save()
		return redirect('game:index', game_url=game_url)
	else:
		robot.delete()
		return render(request, "game/compile_error.html", {})


@login_required
def result(request):
	user_robot_value = request.POST["user_robot"]
	oppo_robot_value = request.POST["oppo_robot"]
	game_url = request.POST["game"]
	game = Game.objects.get(url=game_url)
	user_robot = Robot.objects.get(game=game, user=request.user, name=user_robot_value)
	oppo_robot = Robot.objects.get(
		game=game,
		user=User.objects.get(username=oppo_robot_value.split("-")[0]),
		name=oppo_robot_value.split("-")[1]
	)
	data = {
	"game": game,
	"user_robot": user_robot,
	"oppo_robot": oppo_robot,
	"gameplayer_url": "gameplayer/" + game.url + ".html"
	}
	return render(request, "game/gameplayer.html", data)


@csrf_exempt
@login_required
def compete(request):
	game = Game.objects.get(id=request.POST["game"])
	user_robot = Robot.objects.get(id=request.POST["user_robot"])
	oppo_robot = Robot.objects.get(id=request.POST["oppo_robot"])
	game_script = GAME_SCRIPT_ROOT + str(game.url) + ".py"
	result = subprocess.check_output(["python", game_script, user_robot.code.name, oppo_robot.code.name],
	                                 universal_newlines=True, shell=True)
	return JsonResponse(json.loads(result))